package com.everis.core.mail;

import java.io.Serializable;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.everis.util.EmailBean;

/***
 * 
 * @author vmorepal
 * 
 * Clase utilizada para el envio de mail clasico (sin archivos adjuntos)
 * 
 */

public class EnvioMail implements Serializable {

	public static final String SUCCESS = "SUCCESS";
	
	public static final String ERROR = "ERROR";
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	public static String enviarMail(EmailBean emailBean){
		try {
			String validaMail = validaDatosMail(emailBean); 
			if(validaMail.compareTo(SUCCESS)==0){
				Properties props = new Properties();
				props.put("mail.smtp.host", emailBean.getHost());
				props.put("mail.smtp.port", emailBean.getPort());
				
				Session session = Session.getInstance(props);
				session.setDebug(true);
				
				Message message = new MimeMessage(session);
				message.setFrom(new InternetAddress(emailBean.getDesde()));
				message.setRecipients(Message.RecipientType.TO,
						InternetAddress.parse(emailBean.getPara()));
				if(emailBean.getCopia()!=null){
					message.setRecipients(Message.RecipientType.CC,
							InternetAddress.parse(emailBean.getCopia()));	
				}
				if(emailBean.getCopiaOculta()!=null){
					message.setRecipients(Message.RecipientType.BCC,
							InternetAddress.parse(emailBean.getCopiaOculta()));	
				}
				message.setSubject(emailBean.getAsunto());
				message.setContent(emailBean.getMensaje(), "text/html; charset=utf-8");
				
				Transport.send(message);
				return SUCCESS;
			}			
			return ERROR + ": " + validaMail;
		} catch (Exception e) {
			e.printStackTrace();
			return e.getMessage();
		}
	}
	
	private static String validaDatosMail(EmailBean emailBean){
		if(emailBean!=null){
			if(emailBean.getDesde()==null || emailBean.getDesde().compareTo("")==0){
				return "INGRESE EL FROM DEL CORREO";
			}else if(emailBean.getPara()==null || emailBean.getPara().compareTo("")==0){
				return "INGRESE EL DESTINATARIO DEL CORREO";
			}else if(emailBean.getAsunto()==null || emailBean.getAsunto().compareTo("")==0){
				return "INGRESE EL ASUNTO DEL CORREO";
			}else if(emailBean.getMensaje()==null || emailBean.getMensaje().compareTo("")==0){
				return "INGRESE EL MENSAJE DEL CORREO";
			}else if(emailBean.getHost()==null || emailBean.getHost().compareTo("")==0){
				return "INGRESE EL HOST DEL CORREO";
			}else if(emailBean.getPort()==null || emailBean.getPort().compareTo("")==0){
				return "INGRESE EL PUERTO DEL CORREO";
			}else{
				return SUCCESS;
			}
		}
		return ERROR;
	}
	
	
}
